--- 电池状态管理
-- @module battery
-- @author 小强
-- @copyright openLuat.com
-- @release 2017.11.9

module(..., package.seeall)
CHARGE_FINISH = 2
CHARGING = 1

local LOW_VOLT = 3600
local OFF_VOLT = 3500
local charger = rtos.poweron_reason() == rtos.POWERON_CHARGER
local charging_state
local battStatus, voltage = pmd.param_get()
local lastAlertTime,battoff

function getCharger()
    return charger
end

function getChargingState()
    return charging_state
end

function getVoltage()
    return voltage
end

function islow()
    return voltage < LOW_VOLT and not charger
end

rtos.on(rtos.MSG_PMD, function(msg)
    if msg.charger ~= charger then
        charger = msg.charger
        sys.publish('BATT_CHARGER_IND', charger)
    end
    
    print("chg",msg.charger,msg.voltage,msg.state)

    if not charger then
        if msg.voltage < OFF_VOLT and not battoff then
            battoff = true
            sys.publish('BATT_OFF_IND')
        elseif msg.voltage < LOW_VOLT and (not lastAlertTime or os.time() - lastAlertTime > 600) then -- 10分钟提示一次
            sys.publish('BATT_LOW_IND')
            lastAlertTime = os.time()
        end

        if voltage ~= msg.voltage then
            sys.publish('BATT_VOLT_IND')
        end
    else
        if charging_state ~= msg.state and charging_state == 2 then
            sys.publish('BATT_CHARGING_FINISH')
        end
    end

    voltage = msg.voltage
    charging_state = msg.state
end)

pmd.init {
    batdetectEnable = 0,
    currentFirst = 200,
    currentSecond = 200,
    currentThird = 200,
    intervaltimeFirst = 180,
    intervaltimeSecond = 60,
    intervaltimeThird = 30,
    battlevelFirst = 4100,
    battlevelSecond = 4150,
    pluschgctlEnable = 1,
    pluschgonTime = 5,
    pluschgoffTime = 1,
}
